package co.sanduche.behave.views;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import co.sanduche.behave.R;
import co.sanduche.behave.presenters.FeedPresenter;
import co.sanduche.behave.views.MainActivity.NavigationFragment;
import co.sanduche.models.Models.Mensaje;

public class FeedFragment extends NavigationFragment implements FeedView {
	private FeedAdapter adapter;
	private ListView list;
	private FeedPresenter presenter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.main_feed_fragment,
				container, false);

		list = ((ListView) rootView.findViewById(R.id.feedListFeed));
		adapter = new FeedAdapter(this);
		list.setAdapter(adapter);
		presenter = new FeedPresenter(this);
		return rootView;
	}

	@Override
	public void onResume() {
		super.onResume();
		presenter.resume();
	}

	@Override
	public String getPageTitle() {
		return "Feed";
	}

	public class FeedAdapter extends BaseAdapter {

		private FeedFragment fragment;

		private Map<String, String> imagenes = new HashMap<String, String>();

		private List<Mensaje> mensajes;

		public FeedAdapter(FeedFragment feedFragment) {
			fragment = feedFragment;
		}

		public void setSource(List<Mensaje> mensajes) {
			this.mensajes = mensajes;
			this.notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			if (mensajes != null)
				return mensajes.size() + 1;
			return 1;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (position == getCount() - 1) {
				Button btn = new Button(fragment.getActivity());
				btn.setText("Cargar anteriores");
				btn.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {

						notifyDataSetChanged();
					}
				});
				return btn;
			} else {
				LayoutInflater inflater = fragment.getActivity()
						.getLayoutInflater();
				View rowView = inflater.inflate(R.layout.feed_item_view,
						parent, false);
				TextView sender = (TextView) rowView
						.findViewById(R.id.feedItemLblSender);
				TextView message = (TextView) rowView
						.findViewById(R.id.feedItemLblMessage);
				Mensaje m = mensajes.get(position);
				message.setText(m.getMensaje());

				return rowView;
			}
		}
	}

	@Override
	public void showMensajes(List<Mensaje> arg0) {
		adapter.setSource(arg0);

	}

}
